import {
  Component
} from '@angular/core';
import {
  NavController,
  NavParams,
  ViewController,
  AlertController,
  LoadingController, Events
} from 'ionic-angular';
import {ChangeDetectorRef} from '@angular/core';
import {Storage} from '@ionic/storage'
import {
  Http,
  Headers,
  RequestOptions,
  URLSearchParams
} from '@angular/http';
import {
  baseCommon
} from '../../common/baseCommon';
import {
  AppConfig
} from './../../app/app.config';

/**
 * Generated class for the ChangePurposePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
  selector: 'page-change-purpose',
  templateUrl: 'change-purpose.html',
})
export class ChangePurposePage {

  getMyPurpose = [];
  skills = [];
  remove: any;
  length: number;
  purpose_str: String = '';
  listData: any;
  x: any;
  y: any;

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public storage: Storage,
              public cd: ChangeDetectorRef,
              public alertCtrl: AlertController,
              public http: Http,
              public loadingCtrl: LoadingController,
              public event: Events,
              public viewCtrl: ViewController) {
    this.getMyPurpose = navParams.get('myPurpose');
    for (var n = 0; n < this.getMyPurpose.length; n++) {
      if (n != 0) {
        this.purpose_str += ",";
      }
      this.purpose_str += this.getMyPurpose[n];
    }
    this.storage.set('mySkills', this.getMyPurpose);
  }

  ionViewDidEnter() {
    AppConfig.viewCtrl = this.viewCtrl;
  }


  dismiss() {
    this.viewCtrl.dismiss();
  }

  /**
   * 自定义目的
   *
   * @param {any} $event
   * @memberof ChangePurposePage
   */
  addThisPurpose($event) {
    this.addMypurpose($event.target.innerText);
  }

  /**
   * 移除目的
   *
   * @param {any} $event
   * @memberof ChangePurposePage
   */
  removePurpose($event) {
    this.purpose_str = '';
    let str = $event.target.offsetParent.innerText;
    // console.log(str);
    for (let a = 0; a < this.getMyPurpose.length; a++) {
      if (this.getMyPurpose[a] == str) {
        this.getMyPurpose.splice(a, 1);
      }
    }
    for (let a = 0; a < this.getMyPurpose.length; a++) {
      if (a != 0) {
        this.purpose_str += ",";
      }
      this.purpose_str += this.getMyPurpose[a];
    }
    console.log(this.purpose_str);
  }

  /**
   * 在本页面显示添加的目的（用户不一定保存）
   *
   * @param {any} data
   * @memberof ChangePurposePage
   */
  addMypurpose(data) {
    if (data != undefined && this.getMyPurpose.length <= 2) {
      if (this.purpose_str.length != 0) {
        this.purpose_str += ",";
      }
      this.purpose_str += data;
      this.getMyPurpose = this.purpose_str.split(",");
    } else if (this.getMyPurpose.length = 3) {
      this.showAlert("目的最多设置3个呦！！");
      return;
    } else if (data == undefined) {
      this.showAlert("目的不能为空哦！！");
      return;
    }
  }

  /**
   * 保存目的
   *
   * @memberof ChangePurposePage
   */
  saveTarget() {
    this.storage.get('x').then(val => {
      this.x = val;
    })
    this.storage.get('y').then(val => {
      this.y = val;
    })
    this.storage.get('sessionID').then(val => {
      this.targetUpdate(AppConfig.httpLoc + '/info/targetUpdate', this.purpose_str, this.x, this.y, val);
    })
  }


  /**
   * 弹框
   *
   * @memberof GroupPage
   */
  showPrompt() {
    var changeCtrl = this.viewCtrl;
    let prompt = this.alertCtrl.create({
      title: '自定义目的',
      inputs: [{
        name: 'purpose',
        placeholder: '在此输入自定义目的..'
      },
      ],
      buttons: [{
        text: '我再想想',
        handler: data => {

        }
      },
        {
          text: '确认添加',
          handler: data => {
            this.addMypurpose(data.purpose);
          }
        }
      ]
    });
    AppConfig.viewCtrl = prompt;
    prompt.onDidDismiss(data => {
      AppConfig.viewCtrl = changeCtrl;
    })
    prompt.setCssClass("change_purpose");
    prompt.present();
  }

  /**
   * 弹窗2（添加目的的时候出现异常的情况下出现）
   *
   * @param {any} con
   * @memberof ChangePurposePage
   */
  showAlert(con) {
    let alert = this.alertCtrl.create({
      title: '设置错误!',
      subTitle: con,
      buttons: ['OK']
    });
    alert.present();
  }

  /**
   * 更新目的请求
   *
   * @param {any} apiUrl
   * @param {any} targets
   * @param {any} x
   * @param {any} y
   * @memberof ChangePurposePage
   */
  targetUpdate(apiUrl, targets, x, y, sessionID) {
    let loading = baseCommon.showLoading(this.loadingCtrl, '目的更新中....')
    let headers = new Headers({
      'Content-Type': 'application/x-www-form-urlencoded',
    });

    let options = new RequestOptions({
      headers: headers,
    });

    let pramas: URLSearchParams = new URLSearchParams();

    pramas.set('targets', targets);
    pramas.set('sessionID', sessionID);
    pramas.set('x', x);
    pramas.set('y', y);

    this.http.post(apiUrl, pramas, options)
      .toPromise()
      .then(data => {
        this.listData = data.json();
        loading.dismiss();
        this.viewCtrl.dismiss();
      }, err => {
        console.log(err);
      })
  }


}
